<?xml version="1.0" encoding="utf-8"?>
<Content xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:blueonionsoftware-com:bloget:runtime:data">
  <text>If you ever need to P/Invoke to an API that returns extended error information via the GetLastError function, then you've also probably been through the pain of converting the error code into a usable error message via the FormatMessage API  ... not exactly one of the more user-friendly APIs for managed code callers.

Thankfully, there's a shortcut way to get this message, exposed through the Win32Exception class.  Simply doing this:

&lt;code&gt;string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;&lt;/code&gt;

Will prevent you from needing to call FormatMessage to get an error message for an error code.

Of course you also need to remember to set the SetLastError named parameter on your DllImport attribute to true, and obtain the error code through a call to Marshal.GetLastWin32Error, since P/Invoking to GetLastError directly will generally not work (since the last error may have been set again by another API that the CLR has called).  If you're using VB.Net, Err.LastDllError is also an acceptable way of accessing the last error code.</text>
  <last_update>2007-10-04T00:51:49.5620806Z</last_update>
  <source_title />
  <source_link />
  <comments />
  <references />
  <attachments />
</Content>